#!/usr/bin/env python

"""PyQt4 port of the vsequencer"""

from Sequencer import *
from Config import *

import sys
import os.path

from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.config = VSequencerConfig()
        self.browseButton0 = self.createButton(self.tr("&Browse..."), self.browse0)
        self.browseButton = self.createButton(self.tr("&Browse..."), self.browse)
        self.browseButton1 = self.createButton(self.tr("&Browse..."), self.browsefile0)
        self.browseButton2= self.createButton(self.tr("&Browse..."), self.browsefile)
        
        self.findButton = self.createButton(self.tr("&Process"), self.process)
        self.publishButton = self.createButton(self.tr("P&ublish"), self.process)
        self.quitButton = self.createButton(self.tr("&Quit"), QtCore.SLOT("close()"))
        self.publishButton = self.createButton(self.tr("P&ublish"),self.publish)
        
    
        self.fileComboBox = self.createComboBox(self.tr(""))
        self.directoryComboBox0 = self.createComboBox(self.config.rootPath)
        self.directoryComboBox = self.createComboBox(QtCore.QDir.currentPath())
        if not os.path.exists(self.config.ca_cert):
            self.directoryComboBox1 = self.createComboBox()
#            self.directoryComboBox1 = self.createComboBox(QtCore.QDir.currentPath())
        else:
            self.directoryComboBox1 = self.createComboBox(self.config.ca_cert)
        
        if not os.path.exists(self.config.cert):
            self.directoryComboBox2 = self.createComboBox()
        else:
            self.directoryComboBox2 = self.createComboBox(self.config.cert)
    
        self.fileLabel = QtGui.QLabel(self.tr("Soft name:"))
        self.fileLabel.setFont(QtGui.QFont("Times",15))
        
        self.categoryLabel = QtGui.QLabel(self.tr("Category:"))
        self.categoryLabel.setFont(QtGui.QFont("Times",15))
        
        self.categoryCombobox = QtGui.QComboBox()
        self.categoryCombobox.setFont(QtGui.QFont("Times",15))
        self.categoryCombobox.addItems(["Select a Software category","Accessories",
                                        "Games","Graphics","Internet","Multimedia","Office",
                                        "Programming","System","Other"])
        
        self.textLabel = QtGui.QLabel(self.tr("Source directory:"))
        self.textLabel.setFont(QtGui.QFont("Times",15))
        
        self.directoryLabel = QtGui.QLabel(self.tr("Dest directory:"))
        self.directoryLabel.setFont(QtGui.QFont("Times",15))
                   
        self.cacertLabel = QtGui.QLabel(self.tr("CA cert :"))
        self.cacertLabel.setFont(QtGui.QFont("Times",15))            
        self.certLabel = QtGui.QLabel(self.tr("Cert :"))
        self.certLabel.setFont(QtGui.QFont("Times",15))     
                               
        self.processLabel = QtGui.QLabel()
        self.processLabel.setFont(QtGui.QFont("Times",15))
    
#        self.createFilesTable()
        self.browser = QtGui.QTextBrowser()
        self.browser.setFont(QtGui.QFont("Times",15))
        
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.browser)
        
        buttonsLayout = QtGui.QHBoxLayout()
        buttonsLayout.addStretch()
        buttonsLayout.addWidget(self.findButton)
        buttonsLayout.addWidget(self.publishButton)
        buttonsLayout.addWidget(self.quitButton)
    
        mainLayout = QtGui.QGridLayout()
        mainLayout.addWidget(self.fileLabel, 0, 0)
        mainLayout.addWidget(self.fileComboBox, 0, 1, 1, 3)

        mainLayout.addWidget(self.categoryLabel, 1, 0) 
        mainLayout.addWidget(self.categoryCombobox, 1, 1,1,3)
        
        mainLayout.addWidget(self.textLabel, 2, 0, 1, 2)
        mainLayout.addWidget(self.directoryComboBox0, 2, 1)
        mainLayout.addWidget(self.browseButton0, 2, 2)
        mainLayout.addWidget(self.directoryLabel, 3, 0)
        mainLayout.addWidget(self.directoryComboBox, 3, 1)
        mainLayout.addWidget(self.browseButton, 3, 2)
        mainLayout.addWidget(self.cacertLabel, 4, 0)
        mainLayout.addWidget(self.directoryComboBox1, 4, 1)
        mainLayout.addWidget(self.browseButton1, 4, 2)
        mainLayout.addWidget(self.certLabel, 5, 0)
        mainLayout.addWidget(self.directoryComboBox2, 5, 1)
        mainLayout.addWidget(self.browseButton2, 5, 2)
        
        mainLayout.addLayout(layout, 6, 0, 1, 3)
        mainLayout.addWidget(self.processLabel, 7, 0, 1 ,3)
        mainLayout.addLayout(buttonsLayout, 8, 0, 1, 3)
        self.setLayout(mainLayout)
    
        self.setWindowTitle(self.tr("VSequencer"))
        self.resize(800, 600)
        
    def browse0(self):
        directory = QtGui.QFileDialog.getExistingDirectory(self, self.tr("Find Files"),
                                                           QtCore.QDir.currentPath())
        self.directoryComboBox0.addItem(directory)
        self.directoryComboBox0.setCurrentIndex(self.directoryComboBox0.currentIndex() + 1)
    
    def browse(self):
        directory = QtGui.QFileDialog.getExistingDirectory(self, self.tr("Find Files"),
                                                           QtCore.QDir.currentPath())
        self.directoryComboBox.addItem(directory)
        self.directoryComboBox.setCurrentIndex(self.directoryComboBox.currentIndex() + 1)
    
    def browsefile0(self):
        directory = QtGui.QFileDialog.getOpenFileName(self, self.tr("Find Files"),
                                                           QtCore.QDir.currentPath())
        self.directoryComboBox1.addItem(directory)
        self.directoryComboBox1.setCurrentIndex(self.directoryComboBox0.currentIndex() + 1)
        
    def browsefile(self):
        directory = QtGui.QFileDialog.getOpenFileName(self, self.tr("Find Files"),
                                                           QtCore.QDir.currentPath())
        self.directoryComboBox2.addItem(directory)
        self.directoryComboBox2.setCurrentIndex(self.directoryComboBox0.currentIndex() + 1)
    
    def process(self):
        class SoftnameError(Exception): pass
        class PackagePathError(Exception): pass
        class RootPathError(Exception): pass
        
#        soft_name = str(self.softnameEdit.text())
#        package_path = str(self.packagePathEdit.text())
#        root_path = str(self.rootPathEdit.text())
        softName = str(QtCore.QString(self.fileComboBox.currentText()))
        packagePath = str(QtCore.QString(self.directoryComboBox.currentText()))
        rootPath = str(QtCore.QString(self.directoryComboBox0.currentText()))
#        print softName,packagePath,rootPath
        
        
        try:
            if len(softName) == 0:
                raise SoftnameError, ("The soft name may not be "
                                     "empty.")
            if not os.path.exists(packagePath):
                raise PackagePathError, ("The package path may be "
                                    "exists.")
            if len(rootPath) == 0:
                raise RootPathError, ("The root_path must not be "
                                     "empty.")
            
        except SoftnameError, e:
            QtGui.QMessageBox.warning(self, "Softname Error",
                                unicode(e))
            return
        
        except PackagePathError, e:
            QtGui.QMessageBox.warning(self, "Package path Error",
                                unicode(e))
            return
        
        except RootPathError, e:
            QtGui.QMessageBox.warning(self, "Root path Error",
                                unicode(e))
            return
       
        do_gui_main(softName,rootPath,packagePath)
        self.showXml(rootPath, softName)

    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        button.setFont(QtGui.QFont("Times",15))
        self.connect(button, QtCore.SIGNAL("clicked()"), member)
        return button
    
    def createComboBox(self, text=""):
        comboBox = QtGui.QComboBox()
        comboBox.setFont(QtGui.QFont("Times",15))
        comboBox.setEditable(True)
        comboBox.addItem(text)
        comboBox.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
        return comboBox

    def showXml(self,rootPath,softName):
        xmlfile = os.path.join(rootPath,softName,softName)+".xml"        
        try:
            f = open(xmlfile)
        except IOError,e:
            print "can not open:%s  %s" %(xmlfile,str(e))
            return
        for line in f :
            if not line:
                continue
            text = unicode(line.strip("\n"))
            self.browser.append("%s" %text)
        f.close()
        
    def publish(self):
        class CaCertError(Exception): pass
        class CertError(Exception): pass
        
        softName = str(QtCore.QString(self.fileComboBox.currentText()))
        packagePath = str(QtCore.QString(self.directoryComboBox.currentText()))
        rootPath = str(QtCore.QString(self.directoryComboBox0.currentText()))
        ca_cert = str(QtCore.QString(self.directoryComboBox1.currentText()))
        cert = str(QtCore.QString(self.directoryComboBox2.currentText()))
               
        try:
            if not os.path.exists(ca_cert):
                raise CaCertError, ("CA cert not exists.")
            if not os.path.exists(cert):
                raise CertError, ("Cert not exists.")
        
        except CaCertError,e:
            QtGui.QMessageBox.warning(self, "Ca cert Error",
                                unicode(e))
            return
        
        except CertError,e:
            QtGui.QMessageBox.warning(self, "Cert Error",
                                unicode(e))
            return
        
        
        sequencer = Sequencer(softName, rootPath, packagePath)
	sequencer.xml_generate()
        sequencer.soft_publish()
        self.processLabel.setText("Xml published to %s/%s.xml\nSoft published to  %s/%s"\
                                  %(config.metaFile,softName,config.releasePath,softName))
            
        args = {
                'name'        :   '',
                'snapshot'    :   '',
                'category'    :   '',
                'os'          :   '',
                'price'       :   '',
                'description' :   '', 
        }
        args['name'] = str(QtCore.QString(self.fileComboBox.currentText()))
        args['category'] = str(QtCore.QString(self.categoryCombobox.currentText()))
        args['os'] = 'Linux'
        args['run'] = str(QtCore.QString(self.fileComboBox.currentText()))

        rest_request = ''
        for x in args.keys():
            rest_request = rest_request + '<%s>%s</%s>' % (x, args[x], x)
        rest_request = '<software>%s</software>' % rest_request
      
        url = self.config.url
    
        header_file = run('mktemp')
      
        curl_args = '-X POST -H "Content-Type: text/xml" -H "Accept: text/xml" --cert %s --cacert %s -d "%s" --dump-header  %s %s' % (cert, ca_cert, rest_request,header_file,url)
        result = os.system('curl %s ' % curl_args)
        QtGui.QMessageBox.information(self, "Publish",
                                "published success")
        
def run(cmd):
    """
    Run a shell command and return stdout.
    """
    from subprocess import Popen, PIPE, STDOUT
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
    output = p.stdout.read()
    return output.strip()

def main():
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
    
if __name__ == '__main__':
   main()
